// ==========================================================================
// gin-sns 自动生成model扩展代码列表、增、删，改、查、导出，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/model/module/usertoken/usertoken.go
// author：jon
// ==========================================================================
package usertoken

import (
	"errors"

	"xorm.io/builder"

	"gin-sns/app/ginframe/db"
	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/excel"
	"gin-sns/app/ginframe/utils/page"

	usertokenModel "gin-sns/app/model/module/usertoken"
)

var UsertokenDao = newUsertokenDao()

func newUsertokenDao() *usertokenDao {
	return &usertokenDao{}
}

type usertokenDao struct {
}

//映射数据表
func (d *usertokenDao) TableName() string {
	return "t_user_token"
}

// 插入数据
func (d *usertokenDao) Insert(e *usertokenModel.Entity) (int64, error) {
	return db.Instance().Engine().Table(d.TableName()).Insert(e)
}

// 更新数据
func (d *usertokenDao) Update(e *usertokenModel.Entity) (int64, error) {
	return db.Instance().Engine().Table(d.TableName()).ID(e.Id).Update(e)
}

// 删除
func (d *usertokenDao) Delete(e *usertokenModel.Entity) (int64, error) {
	return db.Instance().Engine().Table(d.TableName()).ID(e.Id).Delete(e)
}

//批量删除
func (d *usertokenDao) DeleteBatch(ids ...int64) (int64, error) {
	return db.Instance().Engine().Table(d.TableName()).In("id", ids).Delete(new(usertokenModel.Entity))
}

// 根据结构体中已有的非空数据来获得单条数据
func (d *usertokenDao) FindOne(e *usertokenModel.Entity) (bool, error) {
	return db.Instance().Engine().Table(d.TableName()).Get(e)
}

// 根据条件查询
func (d *usertokenDao) Find(where, order string) ([]usertokenModel.Entity, error) {
	var list []usertokenModel.Entity
	err := db.Instance().Engine().Table(d.TableName()).Where(where).OrderBy(order).Find(&list)
	return list, err
}

//指定字段集合查询
func (d *usertokenDao) FindIn(column string, args ...interface{}) ([]usertokenModel.Entity, error) {
	var list []usertokenModel.Entity
	err := db.Instance().Engine().Table(d.TableName()).In(column, args).Find(&list)
	return list, err
}

//排除指定字段集合查询
func (d *usertokenDao) FindNotIn(column string, args ...interface{}) ([]usertokenModel.Entity, error) {
	var list []usertokenModel.Entity
	err := db.Instance().Engine().Table(d.TableName()).NotIn(column, args).Find(&list)
	return list, err
}

//根据主键查询数据
func (d *usertokenDao) SelectById(id int64) (*usertokenModel.Entity, error) {
	entity := &usertokenModel.Entity{Id: id}
	have, err := d.FindOne(entity)
	if !have {
		err = errors.New("not found")
		entity = nil
	}
	return entity, err
}

//根据主键删除数据
func (d *usertokenDao) DeleteById(id int64) bool {
	entity := &usertokenModel.Entity{Id: id}
	rs, _ := d.Delete(entity)
	if rs > 0 {
		return true
	}
	return false
}

//批量删除数据记录
func (d *usertokenDao) DeleteByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := d.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//根据条件分页查询数据
func (d *usertokenDao) SelectListByPage(param *usertokenModel.SelectPageReq) ([]usertokenModel.Entity, *page.Paging, error) {
	db := db.Instance().Engine()
	p := new(page.Paging)

	if db == nil {
		return nil, p, errors.New("获取数据库连接失败")
	}

	model := db.Table("t_user_token").Alias("t")

	if param != nil {

		if param.UserId != 0 {
			model.Where("t.user_id = ?", param.UserId)
		}

		if param.Token != "" {
			model.Where("t.token = ?", param.Token)
		}

		if param.ExpiredAt != 0 {
			model.Where("t.expired_at = ?", param.ExpiredAt)
		}

		if param.Status != 0 {
			model.Where("t.status = ?", param.Status)
		}

		if param.BeginTime != "" {
			model.Where("date_format(t.create_time,'%y%m%d') >= date_format(?,'%y%m%d') ", param.BeginTime)
		}

		if param.EndTime != "" {
			model.Where("date_format(t.create_time,'%y%m%d') <= date_format(?,'%y%m%d') ", param.EndTime)
		}
	}

	totalModel := model.Clone()
	total, err := totalModel.Count()

	if err != nil {
		return nil, p, errors.New("读取行数失败")
	}

	p = page.CreatePaging(param.PageNum, param.PageSize, int(total))

	model.Limit(p.Pagesize, p.StartNum)

	var result []usertokenModel.Entity
	err = model.Find(&result)
	return result, p, err
}

// 导出excel
func (d *usertokenDao) SelectListExport(param *usertokenModel.SelectPageReq, head, col []string) (string, error) {
	db := db.Instance().Engine()

	if db == nil {
		return "", errors.New("获取数据库连接失败")
	}

	build := builder.Select(col...).From(d.TableName(), "t")

	if param != nil {

		if param.UserId != 0 {
			build.Where(builder.Eq{"t.user_id": param.UserId})
		}

		if param.Token != "" {
			build.Where(builder.Eq{"t.token": param.Token})
		}

		if param.ExpiredAt != 0 {
			build.Where(builder.Eq{"t.expired_at": param.ExpiredAt})
		}

		if param.Status != 0 {
			build.Where(builder.Eq{"t.status": param.Status})
		}

		if param.BeginTime != "" {
			build.Where(builder.Gte{"date_format(t.create_time,'%y%m%d')": "date_format('" + param.BeginTime + "','%y%m%d')"})
		}

		if param.EndTime != "" {
			build.Where(builder.Lte{"date_format(t.create_time,'%y%m%d')": "date_format('" + param.EndTime + "','%y%m%d')"})
		}
	}

	sqlStr, _, _ := build.ToSQL()
	arr, err := db.SQL(sqlStr).QuerySliceString()

	path, err := excel.DownlaodExcel(head, arr)

	return path, err
}

//获取所有数据
func (d *usertokenDao) SelectListAll(param *usertokenModel.SelectPageReq) ([]usertokenModel.Entity, error) {
	db := db.Instance().Engine()

	if db == nil {
		return nil, errors.New("获取数据库连接失败")
	}

	model := db.Table(d.TableName()).Alias("t")

	if param != nil {

		if param.UserId != 0 {
			model.Where("t.user_id = ?", param.UserId)
		}

		if param.Token != "" {
			model.Where("t.token = ?", param.Token)
		}

		if param.ExpiredAt != 0 {
			model.Where("t.expired_at = ?", param.ExpiredAt)
		}

		if param.Status != 0 {
			model.Where("t.status = ?", param.Status)
		}

		if param.BeginTime != "" {
			model.Where("date_format(t.create_time,'%y%m%d') >= date_format(?,'%y%m%d') ", param.BeginTime)
		}

		if param.EndTime != "" {
			model.Where("date_format(t.create_time,'%y%m%d') <= date_format(?,'%y%m%d') ", param.EndTime)
		}
	}

	var result []usertokenModel.Entity
	err := model.Find(&result)
	return result, err
}
